﻿/// <reference path="../../../Proggy/Scripts/jquery-1.7.2-vsdoc.js" />
/// <reference path="../../../Proggy/Content/ThirdParty/jquery-ui-1.8.21.custom/js/jquery-ui-1.8.21.custom.min.js" />
/// <reference path="../../../Proggy/Content/Scripts/ProggyCore.js" />
/// <reference path="Proggy.CorePropertyTypes.js" />


// static
Proggy.CorePropertyTypes.Tags = function () {


    //https://github.com/aehlke/tag-it/blob/master/README.markdown

    //
    this.Init = function (uniqueId, uniqueUlId, uniqueHidden, formInputName) {

        // get tags div
        var tagsDiv = jQuery("#" + uniqueId);

        // get hidden inputs area
        var hiddenArea = jQuery("#" + uniqueHidden);

        // get ul
        var myTagsUl = jQuery("#" + uniqueUlId);

        // get hidden counter
        var getHiddenCounter = function () {
            return hiddenArea.find("input").size();
        };

        // start options
        var options = { itemName: "IGNORE_THIS" + new Date().toString(),
            fieldName: "IGNORE_THIS" + new Date().toString(),
            onTagAdded: function (evt, tag) {

                // get counter
                var i = getHiddenCounter();

                // get val
                var tagVal = tag.find("span.tagit-label:first").html();


                // add input
                hiddenArea.append("<input type=\"hidden\" value=\"" + tagVal + "\" name=\"" + formInputName + "[" + i + "]\" />");
            },
            onTagRemoved: function (evt, tag) {

                // get val
                var tagVal = tag.find("span.tagit-label:first").html();

                // get matching input
                var matchingInput = hiddenArea.find("input['type=hidden'][value='" + tagVal + "']:first");

                // remove
                matchingInput.remove();

                // iterate
                jQuery.each(hiddenArea.find("input"), function (i, el) {

                    jQuery(el).attr("name", formInputName + "[" + i + "]");

                });

            }
        };

        // get available
        var availableTags = jQuery(window).data(uniqueId + "_locked_tag_data");

        // check available
        if (availableTags != undefined) {
            options.availableTags = availableTags;
            console.log(availableTags);
        };

        // tagit
        myTagsUl.tagit(options);


    };
};

